<?php
require_once('Model/SiteManage.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
class Model_Site
{
    var $sys;

    public function __construct()
    {
        $this->sys = new Model_SiteManage();
    }
    //
    public function insert($data)
    {
        $db = new Model_DB();
        return $db->insert('SITE_CONFIG', $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, 'SITE_CONFIG', $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from SITE_CONFIG where id = " . $db->escape($id) . " and enabled = 1");
        $db->query($sql);
        return $db->fetch();
    }
    public function deleteSite($id)
    {
        $db   = new Model_DB();
        $data = array();
        $data['enabled'] = 0;
        return $this->update($id, $data);
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select count(*) from SITE_CONFIG";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "");
        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select * from SITE_CONFIG";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }
    //
    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        $where[] = "{$prefix}enabled = 1";
        return $where;
    }
    //
    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // 基本情報
            // required
            $keys = explode(',', 'company_name,person_name,tel,email,site_name,url');
            foreach($keys as $key){
                if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                    $err[$key]['NotEmpty'] = true;
                }
            }
            // tel
            $key = 'tel';
            if (!isset($err[$key]) && $validate->TelFax($data[$key], '-')){
                $err[$key]['TelFax'] = true;
            }
            // email
            $key = 'email';
            if (!isset($err[$key]) && $validate->Email($data[$key])){
                $err[$key]['Email'] = true;
            }
            // url
            $key = 'url';
            if (!isset($err[$key]) && $validate->Uri($data[$key])){
                $err[$key]['Uri'] = true;
            }
            // auth_flg
            if ($data['auth_flg'] == 1){
                $keys = explode(',', 'auth_name,auth_user,auth_pwd');
                foreach($keys as $key){
                    if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                        $err[$key]['NotEmpty'] = true;
                    }
                    elseif($key != 'auth_name'){
                        if (!isset($data[$key]) || $validate->Alnum($data[$key])){
                            $err[$key]['Alnum'] = true;
                        }
                    }
                }
            }
        // プラグイン
            $key = 'plugin';
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        // トラッキングコード
            if (isset($data['t_id'])){
                foreach($data['t_id'] as $n => $_){
                    if ($validate->NotEmpty($data['t_name'][$n]) || $validate->NotEmpty($data['t_code'][$n])){
                        $err['tracking'][$n] = true;
                    }
                }
            }
        return empty($err);
    }
    //
    public function getPlugin($site_id)
    {
        $db  = new Model_DB();
        $sql = sprintf("select * from D_SITE_PLUGIN where site_id = %d order by auth_cd asc", $site_id);
        $db->query($sql);
        $plugin = array();
        while($res = $db->fetch()){
            $plugin[] = $res['auth_cd'];
        }
        return $plugin;
    }
    public function updatePlugin($site_id, $plugin = array())
    {
        $installed = $this->getPlugin($site_id);
        $db        = new Model_DB();
        foreach($plugin as $auth_cd){
            if (in_array($auth_cd, $installed)){
                $key = array_search($auth_cd, $installed);
                unset($installed[$key]);
            }
            else{
                $data = array();
                $data['site_id'] = $site_id;
                $data['auth_cd'] = $auth_cd;
                $db->insert('D_SITE_PLUGIN', $data);
            }
        }
        foreach($installed as $auth_cd){
            $data = array();
            $data['site_id'] = $site_id;
            $data['auth_cd'] = $auth_cd;
            $db->delete('D_SITE_PLUGIN', $data);
        }
    }
    //
    public function getTrackingCode($site_id)
    {
        $db  = new Model_DB();
        $sql = sprintf("select * from D_SITE_TRACKING_CODE where site_id = %d order by id asc", $site_id);
        $db->query($sql);
        $track = array();
        while($res = $db->fetch()){
            $track[] = $res;
        }
        return $track;
    }
    public function updateTrackingCode($site_id, $data)
    {
        $db  = new Model_DB();
        $sql = sprintf("select * from D_SITE_TRACKING_CODE where site_id = %d", $site_id);
        $db->query($sql);
        $installed = array();
        while($res = $db->fetch()){
            $installed[] = $res['id'];
        }
        if (isset($data['t_id'])){
            foreach($data['t_id'] as $n => $id){
                $track = array();
                $track['site_id'] = $site_id;
                $track['name']    = $data['t_name'][$n];
                $track['code']    = $data['t_code'][$n];
                $track['enabled'] = 1;
                if (in_array($id, $installed)){
                    $db->update($id, 'D_SITE_TRACKING_CODE', $track);
                    $key = array_search($id, $installed);
                    unset($installed[$key]);
                }
                else{
                    $db->insert('D_SITE_TRACKING_CODE', $track);
                }
            }
        }
        foreach($installed as $id){
            $track = array();
            $track['id'] = $id;
            $db->delete('D_SITE_TRACKING_CODE', $track);
        }
    }
    //
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList('SITE_CONFIG'));
    }
    public function getSiteUrl($site_id)
    {
        $config   = __get_config();
        $site_dir = 'site_'. sprintf('%04d', $site_id);
        return 'http://' . $_SERVER['HTTP_HOST'] . $config['SiteManage']['site_url'] . $site_dir . '/';
    }
    public function getSiteDir($site_id, $mkdir = false)
    {
        $config   = __get_config();
        $site_dir = 'site_'. sprintf('%04d', $site_id);
        if ($mkdir == true){
            chdir(SiteManageRootDir . $config['SiteManage']['site_dir']);
            if (!file_exists($site_dir)){
                mkdir($site_dir);
                chmod($site_dir, 0777);
            }
        }
        return SiteManageRootDir . $config['SiteManage']['site_dir'] . $site_dir . '/';
    }
    //　状態
    public function getStatusMap()
    {
        $map    = array();
        $map[0] = '非公開';
        $map[1] = '公開';
        $map[2] = '仮登録';
        return $map;
    }
    public function getStatusName($id)
    {
        $map = $this->getStatusMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    public function getAuthFlagMap()
    {
        $map    = array();
        $map[1] = '設定する';
        $map[0] = '設定しない';
        return $map;
    }
    public function getMainteFlagMap()
    {
        $map    = array();
        $map[1] = 'メンテナンス中';
        return $map;
    }

     //checkemail
    public function validateEmail(&$data, &$err)
    {
        $validate = new Model_Validate();
        // 基本情報
            // required
            $keys = explode(',', 'toemail,fromemail,bcc,reply,letter_title,letter_content');
            foreach($keys as $key){
                if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                    $err[$key]['NotEmpty'] = true;
                }
            }
            // email
            $key = 'toemail';
            if (!isset($err[$key]) && $validate->Email($data[$key])){
                $err[$key]['Email'] = true;
            }
            $key = 'fromemail';
            if (!isset($err[$key]) && $validate->Email($data[$key])){
                $err[$key]['Email'] = true;
            }
            $key = 'bcc';

            $strvar = explode(";",$data[$key]);
            for($i=0;$i<count($strvar);$i++){
	              if (!isset($err[$key]) && $validate->Email($strvar[$i])){
                $err[$key]['Email'] = true;
              }
}

            $key = 'reply';
            if (!isset($err[$key]) && $validate->Email($data[$key])){
                $err[$key]['Email'] = true;
            }

        return empty($err);
    }

        public function updateEmail($site_id,$data,$emailmap,$dir)
    {
        $db = new Model_DB();
        $sql = sprintf("DELETE FROM M_SITE_EMAIL WHERE SITE_ID = %u and status = '%s'", $site_id,$emailmap);

        $db->query($sql);

        $sql = sprintf("INSERT INTO m_site_email (site_id ,email_id,toemail ,fromemail ,bcc,reply,letter_title,letter_content,u_time,u_user,file_url ,status)VALUES ( '%s',  '%s', '%s',   '%s',  '%s', '%s',  '%s', '%s',CURRENT_TIMESTAMP, CURRENT_TIMESTAMP,  '%s', '%s')",$site_id,$data['id'],$db->escape($data['toemail']),$data['fromemail'],$data['bcc'],$data['reply'],$data['letter_title'],$data['letter_content'],$dir,$emailmap);
        $db->query($sql);

    }

     public function getemail($site_id,$status)
    {
       $db = new Model_DB();
        $sql = sprintf("select * from m_site_email where site_id ='".$db->escape($site_id)."'  and status = '". $db->escape($status) ."'");

        //return $sql;
        $db->query($sql);

        $data  = $db->fetch();
        $arr  = $this->getmailtemp();
        $data["etitle"]  =$arr[$status]."メール";
		return $data ;
               // return $db->fetch();
    }

        //　表示順
    public function getmailtemp()
    {
        $mailtemp = array();
        $mailtemp['user_insert']   = 'ユーザ登録';
        $mailtemp['user_update'] = 'ユーザ更新';
        $mailtemp['order_over'] = '注文完了';
        return $mailtemp;
    }
}
?>